package com.mspersonalized.circumscribedAPI.service;

import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.net.URI;
import java.net.http.HttpClient;


import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Service
public class ShopifyService {
    @Value("${shopify.upload.apiurl}")
    private String apiUrl;

    @Value("${shopify.upload.apiKey}")
    private String apiKey;

    @Value("${shopify.upload.password}")
    private String password;

    @Resource
    private AlyRxfgService alyRxfgService;

    public String uploadImage(MultipartFile file, String filename) {
        String requestUrl = apiUrl + "/admin/api/2023-10/graphql.json";
        JSONObject fileObject = new JSONObject();
        fileObject.put("filename", filename);
        fileObject.put("resource", alyRxfgService.convertFileToBase64(file));
        fileObject.put("mime_type", "image/jpeg");
        fileObject.put("fileSize", file.getSize());

        // 建立连接
        HttpClient httpClient = HttpClient.newHttpClient();
        String credentials = apiKey + ":" + password;
        String base64Credentials = Base64.getEncoder().encodeToString(credentials.getBytes());
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(requestUrl))
                .POST(HttpRequest.BodyPublishers.ofString(fileObject.toString(), StandardCharsets.UTF_8))
                .header("Authorization", "Basic " + base64Credentials)
                .header("Accept","*/*")
                .header("Content-Type", "application/json")
                .build();

        try {
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

            System.out.println("status: "+response.statusCode());
            System.out.println("msg: "+response.body());
            return response.body();
        } catch (Exception e) {
            e.printStackTrace();
        }

    return "";
    }
}
